package com.hyperboost.controller;

import com.hyperboost.constant.MessageConstant;
import com.hyperboost.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * 通用接口
 */
@Slf4j
@RestController
@RequestMapping("/frontend/common")
public class CommonController {

    @Autowired
    private FileStorageService fileStorageService;

    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) {

        log.info("文件上传：{}", file.getOriginalFilename());

        try {
            // 原始文件名
            String originalFilename = file.getOriginalFilename();
            // 文件扩展名
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            // 日期路径
            String datePath = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd")) + "/";
            // 唯一文件名
            String uniqueFilename  = UUID.randomUUID() + extension;
            // 最终文件上传路径：日期路径/随机UUID+扩展名
            String objectName = datePath + uniqueFilename;
            // x-file-storage上传文件
            FileInfo fileInfo = fileStorageService.of(file)
                    .setPath(datePath)
                    .setSaveFilename(uniqueFilename)
                    .upload();

            // 返回文件上传路径
            return Result.success(MessageConstant.UPLOAD_SUCCESS, fileInfo.getUrl());
        } catch (Exception e) {
            return Result.error(MessageConstant.UPLOAD_ERROR);
        }
    }
}
